<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <el-steps :space="300" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="catelist"
                :props="cateProps"
                v-model="addForm.goods_cat"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_title">
              <el-input v-model="addForm.goods_title"></el-input>
            </el-form-item>
            <el-form-item label="商品标图" prop="images">
              <el-input v-model="addForm.title_thumb" v-if="false"></el-input>
              <el-upload
                class="avatar-uploader"
                action="http://shop.cn/api/v1.Qny/upload/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  style="border: 1px dashed #d9d9d9;"
                ></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="是否推荐">
              <el-radio-group v-model="addForm.propaganda">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否包邮">
              <el-radio-group v-model="addForm.goods_transport">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="运费" prop="goods_freight">
              <el-input v-model="addForm.goods_freight"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <!-- 复选框 -->
            <!-- <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.id">
              <el-checkbox-group v-model="item.attr_values">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_values" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>-->
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.id">
              <!-- 复选框 -->
              <el-checkbox-group v-model="checkboxVal">
                <!-- <el-checkbox label="i" v-for="i in item.attr_values" :key="i">{{i}}</el-checkbox> -->

                <el-checkbox
                  :label="cb"
                  v-for="(cb,i) in item.attr_values"
                  :key="i"
                  border
                >{{cb[1]}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-table :data="tableData" border fit highlight-current-row>
              <el-table-column prop="attr_value" label="属性名称" width="515px" />

              <el-table-column label="价格" width="500px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attr_price" placeholder="请输入价格"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存量" width="500px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attr_stock" placeholder="请输入库存量"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_values"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-alert title="添加商品图片,最多上传四张图" type="success" :closable="false" class="mar"></el-alert>
            <el-upload
              action="http://shop.cn/api/v1.Qny/upload/"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="50%" :src="previewPath" alt class="previewImg" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_des" :options="quillOption"></quill-editor>
            <!-- <quill-editor v-model="addForm.goods_des"></quill-editor> -->
            <!-- 添加商品 -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import quillConfig from '../../assets/js/quill-config.js'
import { server } from '../api/index'

export default {
  data() {
    return {
      //富文本编辑器的图片上传
      quillOption: quillConfig,
      activeIndex: 0,
      imageUrl: '',
      addForm: {
        goods_title: '',
        goods_price: 0,
        propaganda: '1',
        goods_transport: '0',
        goods_freight: 0,
        //商品所属的分类数组，逗号隔开
        goods_cat: [],
        //图片的数组
        goods_thumb: [],
        //商品的详情描述
        goods_des: '',
        attrs: [],
        goods_attrs: [],
        title_thumb: ''
      },
      addFormRules: {
        goods_title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      //商品分类列表
      catelist: [],

      cateProps: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      //动态参数列表数据
      manyTableData: [],
      //静态属性
      onlyTableData: [],
      tableData: [],
      checkboxVal: [], // checkboxVal
      dialogImageUrl: '',
      dialogVisible: false,
      //图片预览
      previewPath: ''
    }
  },
  created() {
    this.getArray()
    //获取商品分类数据
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await server.selCategory()
      if (res.code !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.catelist = res.data
      console.log(this.catelist)
    },

    //级联选择器选中变化
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    //切换的前置钩子
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    //单张图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.addForm.title_thumb = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type == 'image/jpeg' ||
        file.type == 'image/png' ||
        file.type == 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async tabClicked() {
      const params = { sel: '1' }
      //证明访问的是动态参数面板
      if (this.activeIndex === '1') {
        const { data: res } = await server.getAttr(this.cateId, params)
        if (res.code !== 200) {
          return this.$message.error('获取动态参数列表失败')
        }
        var ids = []
        var values = []
        var goods_attr = []
        res.data.forEach(item => {
          item.attr_values =
            item.attr_values.length === 0 ? [] : item.attr_values.split(',')
          for (var i = 0; i < item.attr_values.length; i++) {
            ids.push(item.id)
            values.push(item.attr_values[i])
          }
          for (var i = 0; i < ids.length; i++) {
            goods_attr[i] = new Array()
            goods_attr[i].push(ids[i])
            goods_attr[i].push(values[i])
          }
          item.attr_values = []

          for (var i = 0; i < goods_attr.length; i++) {
            if (item.id == goods_attr[i][0]) {
              item.attr_values.push(goods_attr[i])
            }
          }

          // item.attr_values = goods_attr
          // console.log(goods_attr)
        })

        // console.log(values)
        // console.log(ids)

        this.manyTableData = res.data
        console.log(res.data)
      } else if (this.activeIndex === '2') {
        const params = { sel: '2' }
        const { data: res } = await server.getAttr(this.cateId, params)
        if (res.code !== 200) {
          return this.$message.error('获取静态参数列表失败')
        }
        console.log(res.data)
        this.onlyTableData = res.data
      }
    },
    getArray() {
      let newarr = this.checkboxVal.map(item => ({
        name: item,
        price: ''
      }))
      this.tableData = newarr
    },
    //验证有没有相同的存在
    isContained(aa, bb) {
      if (
        !(aa instanceof Array) ||
        !(bb instanceof Array) ||
        aa.length < bb.length
      ) {
        return false
      }
      var aaStr = aa.toString()
      for (var i = 0; i < bb.length; i++) {
        if (aaStr.indexOf(bb[i]) < 0) return false
      }
      return true
    },
    //处理移除图片的操作
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      //1.获取将要删除的图片的临时路径
      const filePath = file.response.data
      //2.从goods_thumb数组，找到这个图片对应的索引值
      const i = this.addForm.goods_thumb.findIndex(x => x === filePath)
      //3.调用数组的splice方法，把图片信息对象，从数组中移除
      this.addForm.goods_thumb.splice(i, 1)
      console.log(this.addForm)
    },
    //处理预览效果
    handlePictureCardPreview(file) {
      this.previewPath = file.response.data
      this.dialogVisible = true
    },
    //监听图片上传成功的事件
    handleSuccess(response) {
      console.log(response)
      //1.拼接得到一个图片信息对象
      const picInfo = response.data
      //2.将图片push到数组
      this.addForm.goods_thumb.push(picInfo)
      console.log(this.addForm)
    },
    //添加商品
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        //执行添加操作
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.id,
            attr_values: item.attr_values.join(',')
          }
          // this.addForm.attrs.push(newInfo)
        })
        this.addForm.goods_attrs = this.tableData
        //处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.id,
            attr_name: item.attr_name,
            attr_value: item.attr_values
          }
          this.addForm.attrs.push(newInfo)
        })
        //发送请求添加商品
        //商品的名称，必须是唯一的
        const { data: res } = await server.addGoods(this.addForm)
        if (res.code !== 200) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功！')
        this.$router.push('/list')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  watch: {
    checkboxVal(valArr) {
      var show = []
      console.log(valArr, 2)
      console.log(this.tableData, 1)
      let newarrs = this.tableData.map(item => ({
        attr_value: item.attr_value,
        attr_price: item.attr_price,
        attr_id: item.attr_id,
        attr_stock: item.attr_stock
      }))

      for (var i = 0; i < newarrs.length; i++) {
        show.push(newarrs[i])
      }

      let newarr = valArr.map(item => ({
        attr_value: item[1],
        attr_id: item[0],
        attr_price: '',
        attr_stock: item.attr_stock
      }))

      var exit = this.isContained(show, newarr)

      if (exit == false) {
        show.push(newarr.pop())
      } else {
        // console.log(show, 1)
        // console.log(newarr)
        //判断相同的值
        var result = []
        for (var i = 0; i < show.length; i++) {
          var obj = show[i]
          var attr_value = obj.attr_value
          var isExist = false
          for (var j = 0; j < newarr.length; j++) {
            var aj = newarr[j]
            var n = aj.attr_value
            if (n == attr_value) {
              isExist = true
              break
            }
          }
          if (!isExist) {
            result.push(obj)
          }
        }

        for (var i = 0; i < show.length; i++) {
          if (show[i].attr_value.indexOf(result[0].attr_value) > -1) {
            // console.log(show[i])
            // console.log(result[0])
            if (show[i] == result[0]) {
              show.splice(i, 1)
            }
          }
        }
      }
      console.log(show)
      this.tableData = show
    }
  }
}
</script>
<style scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.mar {
  margin-bottom: 10px;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>